package com.qst.controller;

import com.qst.BaseServlet;
import com.qst.ExamException;
import com.qst.RequestUtil;
import com.qst.WebUtil;
import com.qst.entity.Team;
import com.qst.entity.TestPersonnel;
import com.qst.entity.User;
import com.qst.mapper.UserMapper;
import com.qst.service.TeamService;
import com.qst.service.TestPersonnelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/testPersonnel")
public class TestPersonnelController extends BaseServlet {

    @Autowired
    @Qualifier("testPersonnelServiceImpl")
    TestPersonnelService  testPersonnelService;
    @Autowired
    @Qualifier("teamServiceImpl")
    private TeamService teamService;
    @Autowired
    private  UserMapper userMapper;

    @RequestMapping("/select.action")
    public String select(HttpServletRequest req) {
        int teamId= RequestUtil.getInt(req, "teamId");
        String name=RequestUtil.getString(req, "stuname");
        String phone=RequestUtil.getString(req, "phone");
        List<TestPersonnel> testPersonnel=testPersonnelService.query(teamId,name,phone);
        req.setAttribute("testPersonnel", testPersonnel);
        List<Team> teamList = teamService.findAll();
        req.setAttribute("teamList", teamList);
        return "forward:/testPersonnel/list.jsp";
    }
    @RequestMapping("/list.action")
    public String list(HttpServletRequest req) {
//        int i = Integer.parseInt(tid);
        int tid = RequestUtil.getInt(req, "tid");
        List<TestPersonnel> testPersonnelList = testPersonnelService.findByTeamId(tid);
        req.setAttribute("testPersonnel", testPersonnelList);
        List<Team> teamList = teamService.findAll();
        req.setAttribute("teamList", teamList);
        return "forward:/testPersonnel/list.jsp";
    }
    @RequestMapping("/view.action")
    public String view(HttpServletRequest req) {
        int id = RequestUtil.getInt(req, "id");
        TestPersonnel testPersonnel = testPersonnelService.findById(id);
        req.setAttribute("testPersonnel", testPersonnel);
        return "forward:/testPersonnel/view.jsp";
    }
    @RequestMapping("/edit.action")
    public String edit(HttpServletRequest req) {
        int id = RequestUtil.getInt(req, "id");
        TestPersonnel testPersonnel = testPersonnelService.findById(id);
        req.setAttribute("testPersonnel", testPersonnel);
        return "forward:/testPersonnel/edit.jsp";
    }
    @RequestMapping("/delete.action")
    public String delete(HttpServletRequest req) {
        int id = RequestUtil.getInt(req, "id");
        TestPersonnel testPersonnel = testPersonnelService.deleteTestPersonnel(id);
        req.setAttribute("testPersonnel", testPersonnel);
        return "redirect:/testPersonnel/list.action?tid=" + testPersonnel.getTeamId();
    }
    @RequestMapping("/add.action")
    public String add(HttpServletRequest req) {
        User user = new User();
        req.getParameter("");
        user.setId(RequestUtil.getInt(req, "id"));
        user.setLogin(RequestUtil.getString(req, "login"));
        user.setPasswd(User.PASSWORD);
        user.setName(RequestUtil.getString(req, "name"));
        user.setType(RequestUtil.getInt(req, "type"));
        user.setStatus(RequestUtil.getInt(req, "status"));
        TestPersonnel s = new TestPersonnel();
        s.setUser(user);
        s.setGender(RequestUtil.getString(req, "gender"));
        s.setPhone(RequestUtil.getString(req, "login"));
        s.setTeamId(RequestUtil.getInt(req, "teamId"));
        s.setBirthDate(RequestUtil.getDate(req, "birthDate"));
            User login = userMapper.findByLogin(s.getPhone());
            if(login != null){
                addMessage(req, "该手机号已经存在！");
                int teamId=RequestUtil.getInt(req, "teamId");
                req.setAttribute("teamId", teamId);
                return "forward:/testPersonnel/create.jsp";
            }else {
                addMessage(req, "参测人员添加成功");
                testPersonnelService.addTestPersonnel(s);
                return "redirect:/testPersonnel/select.action?teamId="+s.getTeamId();
            }
    }
    @RequestMapping("/update.action")
    public String update(HttpServletRequest req) {
        User user = new User();
        user.setId(RequestUtil.getInt(req, "id"));
        user.setName(RequestUtil.getString(req, "name"));
        user.setStatus(Integer.parseInt(RequestUtil.getString(req, "status")));
        TestPersonnel testPersonnel = new TestPersonnel();
        testPersonnel.setId(user.getId());
        testPersonnel.setUser(user);
        Date date = Date.valueOf(RequestUtil.getString(req, "birthDate"));
        testPersonnel.setBirthDate(date);
        testPersonnel.setPhone(RequestUtil.getString(req, "phone"));
        testPersonnel.setGender(RequestUtil.getString(req, "gender"));
            testPersonnelService.updateTestPersonnel(testPersonnel);
            return "redirect:/testPersonnel/view.action?id=" + user.getId();
    }


    @GetMapping("/import.action")
    public String Import(HttpServletRequest req) {
        //WebUtil.forward(req, resp, "/testPersonnel/import.jsp");
        return "/testPersonnel/import";
    }

    @PostMapping("/import.action")
    public String Import(HttpServletRequest req, @RequestParam("file") MultipartFile file) throws ServletException, IOException {
        int tid = RequestUtil.getInt(req, "tid");
        //Part part = req.getPart("file");
        if (file.isEmpty()) {
            addError(req, "文件为空，请上传文件");
            return "/testPersonnel/import"; // 假设这是处理错误的页面或重定向
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8));
        String line;
        List<TestPersonnel> testPersonnelList = new ArrayList<>();
        while ((line = reader.readLine()) != null) {
            String[] data = line.split(",");
            if (data.length < 4) {
                addError(req, "导入文件格式错误:" + line);
                //WebUtil.forward(req, resp, "/testPersonnel/import.jsp");
                return "/testPersonnel/import";
            }
            TestPersonnel testPersonnel = new TestPersonnel();
            User user = new User();
            testPersonnel.setTeamId(tid);
            testPersonnel.setUser(user);
            testPersonnel.setPhone(data[0]);
            user.setName(data[1]);
            testPersonnel.setGender(data[2]);
            testPersonnel.setBirthDate(Date.valueOf(data[3]));
            testPersonnelList.add(testPersonnel);
        }
        try {
            testPersonnelService.importTestPersonnel(testPersonnelList);
            addMessage(req, "成功导入" + testPersonnelList.size() + "个参测人员");
            //WebUtil.redirect(req, resp, "/testPersonnel/list.action?tid=" + tid);
            return "redirect:/testPersonnel/list.action?tid=" + tid;
        } catch (ExamException ex) {
            addError(req, ex.getMessage());
            //WebUtil.redirect(req, resp, "/team/list.action");
            return "redirect:/team/list.action";
        }
    }

}
